package com.bbs.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@Service
public class FileUploadService {

    @Value("${upload.path}")
    private String uploadPath; // 配置文件中指定的上传路径

    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择文件进行上传.";
        }

        try {
            // 确保上传目录存在，如果不存在则创建
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 获取文件名
            String fileName = StringUtils.cleanPath(
                    Objects.requireNonNull(file.getOriginalFilename()));

            // 检查文件名是否包含无效字符
            if (fileName.contains("..")) {
                return "文件名包含无效路径序列.";
            }

            // 将文件写入上传目录
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            return "文件上传成功: " + fileName;
        } catch (IOException e) {
            return "文件上传失败: " + e.getMessage();
        }
    }
}
